package org.apache.sad.core.framework.compress.impl;

import java.util.zip.Deflater;

import org.apache.sad.core.framework.compress.IDataCompresser;

import org.apache.sad.core.framework.utils.Base64;
import org.apache.sad.core.framework.utils.ObjectUtils;

public class DataCompresserImpl implements IDataCompresser {

    private static final String DEFAULT_ENCODING = "UTF-8";

    public String compressData(String textMsg, String encoding) throws Exception {
        if (textMsg == null) {
            //LOGGER.warn("Text message is null.");
            return null;
        }

        if (encoding == null){
            //LOGGER.warn("encoding name is null.");
            return null;
        }

        byte[] rawData = textMsg.getBytes(encoding);
        byte[] compressed = ObjectUtils.compressData(rawData, Deflater.BEST_COMPRESSION);
        //11.04 - AQ only supports text message
        return Base64.encode(compressed);
    }

    public String decompressData(String compressed, String encoding) throws Exception {
        if (compressed == null) {
            //LOGGER.warn("Compressed message is null.");
            return null;
        }

        if (encoding == null){
            //LOGGER.warn("encoding name is null.");
            return null;
        }

        //11.04 EEG AQ only supports text message
        byte[] data = Base64.decode(compressed);
        byte[] result = ObjectUtils.decompressData(data);
        return new String(result, 0, result.length, encoding);
    }

    public String compressData(String textMsg) throws Exception {
        return compressData(textMsg, DEFAULT_ENCODING);
    }

    public String decompressData(String compressed) throws Exception {
        return decompressData(compressed, DEFAULT_ENCODING);
    }
}
